//
//  XQHomeContainerController.m
//  JoinPeso
//
//  Created by 小琦 on 2024/11/18.
//

#import "XQHomeContainerController.h"
#import "XQHomeNavBarView.h"
#import "XQHomeTopCardView.h"
#import "XQHomeBigCardView.h"
#import "XQHomeSmallCardView.h"
#import "XQAboutUsController.h"
#import "MJRefresh/MJRefresh.h"
#import "XQDevice.h"

#import "XQAuthenticationController.h"
#import "XQLoginViewController.h"

@interface XQHomeContainerController ()
@property (nonatomic,strong) XQHomeNavBarView *navView;
@property (nonatomic,strong) UIView *mainView;
@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) XQHomeTopCardView *topCardView;
@property (nonatomic,strong) UIButton *applyButton;
@property (nonatomic,strong) XQHomeBigCardView *bigCardView;
@property (nonatomic,strong) XQHomeSmallCardView *smallCardView;
@property (nonatomic,copy) NSDictionary *dataDic;
@property (nonatomic, assign) BOOL isClicked;

@end

@implementation XQHomeContainerController {
    BOOL _isFirstLoad;
}

- (void)dealloc {
    // 移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationBar.hiddenBack = YES;
    [self makeUI];
    [self makeConstraints];
    
    [self initBattery];
    
    [XQHUD showLoadingInView:self.view];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self refreshData];
    if (!_isFirstLoad) {
        _isFirstLoad = YES;
        [self checkLocationAuthorization];
    }
}

- (void)makeUI {
    if (@available(iOS 11, *)) {
        self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F3F4F8"];
    [self.view addSubview:self.navView];
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.mainView];
    [self.mainView addSubview:self.topCardView];
    [self.mainView addSubview:self.applyButton];
}

- (void)makeConstraints{
    [self.navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo([UIScreen mainScreen].statusBarHeight);
        make.left.right.equalTo(@0);
        make.height.mas_equalTo(44);
    }];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo([UIScreen mainScreen].topHeight);
        make.left.right.equalTo(@0);
        make.bottom.offset(-[UIScreen mainScreen].bottomHeight - 49);
    }];
    [self.mainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
        make.width.mas_equalTo([UIScreen mainScreen].width);
    }];
    [self.topCardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@8);
        make.left.right.equalTo(@0);
        make.height.mas_equalTo(220);
    }];
    [self.applyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topCardView.mas_bottom).offset(10);
        make.left.equalTo(@12);
        make.right.equalTo(@-12);
        make.height.mas_equalTo(45);
    }];
}

- (void)refreshData {
    @weakify(self)
    [XQAFNetworking getWithUrl:[XQNetManager getAbsolutePath:@"/direct/disaster"] pars:@{} callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        @strongify(self);
        [XQHUD hideLoadindInView:self.view];
        [self.scrollView.mj_header endRefreshing];
        if ([responseObject[@"concept"] integerValue] == 0) {
            self.dataDic = responseObject[@"accomplish"];
            
            [self updateCustomer];
            
            [self reportData];
        }
        
        [self updatePageData];
    }];
}

- (void)reportData {
    [XQGoogleMarket reportIdfv];
    [XQGoogleMarket reportDevice];    
    // 定位权限
    [[XQLocationManager manager] startLocation];
}

- (void)checkLocationAuthorization {
    if (@available(iOS 14.0, *)) {
        CLLocationManager *locationManager = [[CLLocationManager alloc] init];
        if (locationManager.authorizationStatus == kCLAuthorizationStatusDenied) {
            if ([XQToolManager manager].needLocationPop) {
                if ([self checkAndShowAlert]) {
                    [XQAlertController showAccessDeniedAlert:self message:@"To offer you personalized loan options and services in your area, we need access to your location. Please enable location services for a tailored experience."];
                }
            }
        }
    } else {
       
    }
}

#pragma mark - private

- (void)applyClick {
    if (!self.isClicked) {
        self.isClicked = YES;
        [self checkProductId:self.cardId];
    }
}

- (void)customerClick {
    XQWebViewController *vc = [[XQWebViewController alloc] init];
    NSDictionary *etc = self.dataDic[@"etc"];
    vc.url = [XQNetManager getWebUrlAbsolutePath:etc[@"telef"]];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)checkProductId:(NSString *)cardId {
    if (cardId.length <= 0) return;;
        
    NSDictionary *dic = @{
        @"accommodate" : cardId
    };
    
    [XQHUD showLoadingInView:self.view];
    @weakify(self)
    [XQAFNetworking postWithUrl:[XQNetManager getAbsolutePath:@"/direct/scenarios"] pars:dic callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        @strongify(self);
        [XQHUD hideLoadindInView:self.view];
        self.isClicked = NO;
        // 需要登录
        if ([responseObject[@"concept"] integerValue] == -2) {
            XQLoginViewController *vc = [XQLoginViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }else {
            NSDictionary *accomplish = responseObject[@"accomplish"];
            NSString *url = accomplish[@"aviation"];
            [XQRouter jumpFromController:self url:url];
        }
    }];
}

- (void)updatePageData{
    if ([self.dataDic[@"rakuten"] isKindOfClass:[NSArray class]]) {
        NSArray *array = self.dataDic[@"rakuten"];
        
        NSArray *topCard = [NSArray array];
        NSArray *banner = [NSArray array];
        NSArray *listCard = [NSArray array];
       
        BOOL isShowBigCard = YES;
        for (NSDictionary *dic in array) {
            if ([dic[@"spacemobile"] isEqualToString:@"lba"]) {
                banner = dic[@"ast"];
            }else if ([dic[@"spacemobile"] isEqualToString:@"lbb"]) {
                topCard = dic[@"ast"];
                isShowBigCard = YES;
            }else if ([dic[@"spacemobile"] isEqualToString:@"lbc"]) {
                topCard = dic[@"ast"];
                isShowBigCard = NO;
            }else if ([dic[@"spacemobile"] isEqualToString:@"lbd"]) {
                listCard = dic[@"ast"];
            }
        }
        
        NSDictionary *cardDic = topCard.firstObject;
        self.cardId = [cardDic[@"viasat"] description];
        [self setCardData:cardDic];
        
        [self.bigCardView removeFromSuperview];
        [self.smallCardView removeFromSuperview];

        
        if (isShowBigCard) {
            self.smallCardView.hidden = YES;
            self.bigCardView.hidden = NO;
            [self.mainView addSubview:self.bigCardView];
            [self.bigCardView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.applyButton.mas_bottom).offset(16);
                make.left.right.equalTo(@0);
                make.bottom.equalTo(@-4);
            }];
            [self.bigCardView setDataSource:banner];
        }else {
            self.bigCardView.hidden = YES;
            self.smallCardView.hidden = NO;
            [self.mainView addSubview:self.smallCardView];
            [self.smallCardView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.applyButton.mas_bottom).offset(16);
                make.left.right.equalTo(@0);
                make.bottom.equalTo(@-4);
            }];
            [self.smallCardView setDataSource:listCard];
        }
    }
}

- (void)updateCustomer {
    NSDictionary *etc = self.dataDic[@"etc"];
    [self.navView setLogo:etc[@"nica"]];
}

- (void)setCardData:(NSDictionary *)cardDic {
    NSString *price = cardDic[@"china"];
    NSArray *priceArr = [price componentsSeparatedByString:@" "];
    if (priceArr.count == 2) {
        [self.topCardView setPrice:priceArr.lastObject];
    }else {
        [self.topCardView setPrice:@"0"];
    }
    
    [self.topCardView setTopValue:cardDic[@"way"]];
    [self.applyButton setTitle:cardDic[@"hughes"] forState:UIControlStateNormal];
    [self.topCardView setConflicts:cardDic[@"conflicts"]];
    [self.topCardView setEncountered:cardDic[@"encountered"]];
    [self.topCardView setArticles:cardDic[@"articles"]];
    [self.topCardView setTrademark:cardDic[@"trademark"]];
}

- (BOOL)checkAndShowAlert {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    // 获取上次弹窗显示的日期
    NSDate *lastAlertDate = [defaults objectForKey:@"LastAlertDate"];
    
    // 获取当前日期和时间
    NSDate *nowDate = [NSDate date];

    NSDate *datePlus24Hours = [lastAlertDate dateByAddingTimeInterval:24 * 60 * 60];
    
    BOOL flag = [nowDate compare:datePlus24Hours] == NSOrderedDescending;

    // 如果没有上次日期，或上次日期早于今天的午夜，则弹出弹窗
    if (!lastAlertDate || flag) {
        
        // 更新上次弹窗显示的日期
        [defaults setObject:nowDate forKey:@"LastAlertDate"];
        [defaults synchronize];
        return YES;
    }else {
        return NO;
    }
}

- (void)initBattery {
    // 启用电池监控
    [UIDevice currentDevice].batteryMonitoringEnabled = YES;
    // 获取电池信息
   [self getBatteryInfo];
   
   // 监听电池状态变化
   [[NSNotificationCenter defaultCenter] addObserver:self
                                                selector:@selector(batteryStateDidChange:)
                                                    name:UIDeviceBatteryStateDidChangeNotification
                                                  object:nil];
}

- (void)getBatteryInfo {
    
    NSString *week = @"";
    NSString *train = @"";
    
    // 获取电量百分比
    float batteryLevel = [UIDevice currentDevice].batteryLevel;
    // 判断电量是否有效
    if (batteryLevel >= 0) {
        week = [NSString stringWithFormat:@"%.0f", batteryLevel * 100];
    }

    // 获取充电状态
    UIDeviceBatteryState batteryState = [UIDevice currentDevice].batteryState;
    if (batteryState == UIDeviceBatteryStateCharging) {
        train = @"1";
    }else {
        train = @"0";
    }
    
    NSDictionary *dic = @{
        @"week" : week,
        @"train" : train
    };
    [XQToolManager manager].representatives = dic;
}

- (void)batteryStateDidChange:(NSNotification *)notification {
    // 电池状态变化时重新获取电池信息
    [self getBatteryInfo];
}

#pragma mark - lazy

- (XQHomeNavBarView *)navView {
    if (!_navView) {
        _navView = [[XQHomeNavBarView alloc] init];
        @weakify(self);
        _navView.customerHandle = ^{
            @strongify(self);
            [self customerClick];
        };
    }
    return _navView;
}

- (UIView *)mainView {
    if (!_mainView) {
        _mainView = [[UIView alloc] init];
    }
    return _mainView;
}

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        
        _scrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self refreshData];
        }];
    }
    return  _scrollView;
}

- (XQHomeTopCardView *)topCardView {
    if (!_topCardView) {
        _topCardView = [[XQHomeTopCardView alloc] init];
        [_topCardView setUserInteractionEnabled:YES];
        [_topCardView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(applyClick)]];
    }
    return _topCardView;
}

- (UIButton *)applyButton {
    if (!_applyButton) {
        _applyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _applyButton.layer.cornerRadius = 22.5;
        _applyButton.backgroundColor = [UIColor colorWithHexString:@"#4C1DEE"];
        _applyButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
        [_applyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_applyButton addTarget:self action:@selector(applyClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _applyButton;
}

- (XQHomeBigCardView *)bigCardView {
    if (!_bigCardView) {
        _bigCardView = [[XQHomeBigCardView alloc] init];
        _bigCardView.hidden = YES;
        _bigCardView.layer.masksToBounds = YES;
        @weakify(self);
        _bigCardView.didSelectHandle = ^(NSString * _Nonnull url) {
            @strongify(self);
            [XQRouter jumpFromController:self url:url];
        };
    }
    return  _bigCardView;
}

- (XQHomeSmallCardView *)smallCardView {
    if (!_smallCardView) {
        _smallCardView = [[XQHomeSmallCardView alloc] init];
        _smallCardView.hidden = YES;
        _smallCardView.layer.masksToBounds = YES;
        @weakify(self);
        _smallCardView.didSelectIndex = ^(NSString * _Nonnull cardId) {
            @strongify(self);
            if (!self.isClicked) {
                self.isClicked = YES;
                [self checkProductId:cardId];
            }
        };
    }
    return _smallCardView;
}

@end
